package com.qububu.emporium.orderform.control;

import static com.qububu.utils.ParamConverter.assertNotEmpty;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qububu.common.user.dto.UserInfoDto;
import com.qububu.emporium.orderform.dto.OrderFormInfoDto;
import com.qububu.emporium.orderform.dto.OrderFormInfoDto.OrderPayType;
import com.qububu.emporium.orderform.dto.OrderFormInfoDto.OrderStatus;
import com.qububu.emporium.orderform.service.OrderFormService;
import com.qububu.emporium.shoppingCart.dto.CartSaveGoodsMessageDto;
import com.qububu.systemBase.exceptions.ValidateFailException;
import com.qububu.utils.DateUtil;
import com.qububu.utils.ParamConverter;
import com.qububu.utils.SystemConstants;
import com.qububu.utils.SystemUtil;

@Controller
@RequestMapping("/orderForm")
public class OrderFormControl {

	@Resource
	private OrderFormService orderFormService;
	
	/**
	 * @author ZCW
	 * @功能 订单查询
	 * @备注 
	 * */
	@RequestMapping("/admin/getOrderForms")
	public String getOrderForms(HttpServletRequest request, HttpServletResponse response){
		
		List<OrderFormInfoDto> orderList = orderFormService.getOrderFormListByOrderStatus(OrderStatus.undisposed.toIntValue());
		
		request.setAttribute("orderList", orderList);
		
		return "adminOrderForm";
	}
	
	/**
	 * 给出对应订单的商品
	 * */
	@RequestMapping("/admin/getOrderGoods")
	@ResponseBody
	public Map<String, Object> getOrderGoods(HttpServletRequest req) {
		String orderNo = assertNotEmpty(req.getParameter("on"));// 获取订单号
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<CartSaveGoodsMessageDto> goodsList = orderFormService.getGoodsListByOrderNo(orderNo);
		resultMap.put("goodsList", goodsList);
		resultMap.put("result", SystemConstants.AJAX_SUCCESS);
		return resultMap;
	}
	
	/**
	 * 改变订单状态
	 * */
	@RequestMapping("/admin/changeOrderStatus")
	@ResponseBody
	public Map<String, Object> changeOrderStatus(HttpServletRequest req) {
		String orderId = assertNotEmpty(req.getParameter("oi"));
		String status = assertNotEmpty(req.getParameter("status"));// 获取状态
		orderFormService.doChangeOrderStatus(orderId, OrderStatus.getOrderStatus(status).toIntValue());
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("result", SystemConstants.AJAX_SUCCESS);
		return resultMap;
	}
	
	private boolean cheak(HttpServletRequest request) {
		String cartKey = assertNotEmpty(request.getHeader(SystemConstants.CART_IDENTIFICATION_KEY));
		if (! request.getSession().getAttribute(SystemConstants.CART_IDENTIFICATION_KEY).equals(cartKey)) {
			return false;
		}
		
		return true;
	}
	/**
	 * @throws Exception 
	 * @功能 生成订单
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/generateOrder")
	@ResponseBody
	public Map<String, Object> generateOrder(HttpServletRequest request, HttpServletResponse response) throws Exception{
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (!cheak(request)) { // 如果非法进入
			resultMap.put("result", SystemConstants.AJAX_FAILED_ALERT);
			return resultMap;
		}
		String orderId = SystemUtil.getUUIDString();
		String payType = request.getParameter("payType") == null ? "COD" : request.getParameter("payType");
		String orderReceiveDt = assertNotEmpty(request.getParameter("orderReceiveDt")); // 年月日形式
		String buyerName = assertNotEmpty(request.getParameter("buyerName"));
		String buyerPhoneNumber = ParamConverter.assertPhoneNumberString(assertNotEmpty(request.getParameter("buyerPhoneNumber")));
		String buyerAddr = SystemUtil.convertSpecialMark(assertNotEmpty(request.getParameter("buyerAddr")));
		String remark = request.getParameter("remark") == null ? "" : SystemUtil.convertSpecialMark(request.getParameter("remark"));

		String orderNo = orderFormService.genOrderFormNumber();
		
		OrderFormInfoDto orderForm = new OrderFormInfoDto(orderId, orderNo);
		HttpSession session = request.getSession();
		Map<String, Object> cartMap = (Map<String, Object>) session.getAttribute(session.getId());
		orderForm.setOrderAmount((Double) cartMap.get(SystemConstants.CART_TOTAL_PRICE_KEY));
		orderForm.setOrderCreateDttm(DateUtil.convertCurrentDTTMtoInt());
		orderForm.setOrderPayType(OrderPayType.getOrderPayType(payType));
		orderForm.setOrderReceiveDt(changeDate(orderReceiveDt));
		orderForm.setRemark(remark);
		orderForm.setUserAddr(buyerAddr);
		orderForm.setUserName(buyerName);
		orderForm.setUserPhoneNumber(buyerPhoneNumber);
		orderForm.setStatus(OrderStatus.undisposed);
		
		Map<String, CartSaveGoodsMessageDto> goodsMap = (Map<String, CartSaveGoodsMessageDto>) cartMap.get(SystemConstants.CART_GOODS_MAP);
		
		if (orderFormService.doAddOrderForm(orderForm, goodsMap)) {
			resultMap.put("on", orderNo);// 订单
			resultMap.put("result", SystemConstants.AJAX_SUCCESS);
			
			return resultMap;
		}
		
		resultMap.put("result", SystemConstants.AJAX_FAILED_ALERT);
		return resultMap;
	}
	
	/**
	 * 将字符串转换为时间
	 * */
	private int changeDate(String date) {
		
		if ("today".equals(date)) {
			return DateUtil.convertCurrentDTTMtoInt();
		}
		
		if ("tomorrow".equals(date)) {
			return (DateUtil.convertCurrentDTTMtoInt() + 24 * 60 * 60);
		}
		
		throw new ValidateFailException("input string is not date string:" + date);
	}
	
	/**
	 * @功能 确认订单
	 * @备注 
	 * */
	@RequestMapping("/confirm_order")
	public String confirmOrder() {
		
//		System.out.println("|-------{info}-------BuyControl-->confirmOrder----------|");
		
		return "confirm_order";
	}
	
	/**
	 * @author HQ
	 * @功能 根据userId查出订单列表
	 */
	@RequestMapping("/queryOrderList")
	public String queryOrderFormByUserId(HttpServletRequest request, HttpServletResponse response){
		
		UserInfoDto userInfoDto = (UserInfoDto) request.getSession().getAttribute(SystemConstants.LOGINUSER_SESSION_NAME);
		String userId = String.valueOf(userInfoDto.getUserId());
		
		List<OrderFormInfoDto> orderFormInfoList = orderFormService.getQueryOrderListByUserId(userId);
		request.setAttribute("orderFormInfoList", orderFormInfoList);
		
		return "orderList";
	}
	
	/**
	 * @author HQ
	 * @功能 根据订单号查询商品详细信息
	 */
	@RequestMapping("/queryOrderInfoDetal")
	public String queryOrderFormInfoDetalByOrderNo(HttpServletRequest request, HttpServletResponse response){
		
		String orderNo = assertNotEmpty(request.getParameter("orderNo"));
		OrderFormInfoDto orderFormInfoDto = orderFormService.getQueryOrderInfoDetalByOrderNo(orderNo);
		request.setAttribute("orderInfoDetal", orderFormInfoDto);
		
		return "orderInfoDetal";
	}
	
	/**
	 * @author HQ
	 * @功能 删除
	 */
	@RequestMapping("/ajaxDoDeleteOrderForm")
	@ResponseBody
	public boolean doDeleteOrderFormByOrderNo(HttpServletRequest request, HttpServletResponse response){
		
		String orderNo = assertNotEmpty(request.getParameter("orderNo"));
		orderFormService.doDeleteOrderFormByOrderNo(orderNo);
		
		return true;
	}
}
